package com.bootdo.collector.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import java.io.IOException;
import java.util.Collections;

public class ESParse {
    /**
     * 执行es查询语句，并返回json格式查询结果
     *
     * @param query
     *            json字符串格式的 查询语句
     * @return
     */
    public static String execQuery(RestClient restClient , String query, String url) {
        HttpEntity httpEntity = new NStringEntity(query, ContentType.APPLICATION_JSON);
        String  respStr = null;
        int i = 0;
        // 考虑到国内外网络状况，当请求失败时重复尝试三次
        while (respStr == null && i++ < 3) {
            try {
                Response response = restClient.performRequest("POST", url,
                        Collections.<String, String>emptyMap(), httpEntity);
                respStr = EntityUtils.toString(response.getEntity());

            } catch (IOException e) {
                //log.error(e.getMessage(), e);
            }
        }
        return respStr;
    }

    public static JSONObject getfirsthits(String res) {

        return  JSON.parseObject(res).getJSONObject("hits");
    }

    public static Long getTotal(JSONObject object){
        return object.getLong("total");
    }

    public static Long getTotal2(String res) {return  getTotal(getfirsthits(res));}
}
